//
//  YKStack.c
//  data01
//
//  Created by gaofeng on 2021/3/27.
//
#include "YKStack.h"
#include <stdlib.h>

void InitStack(SqStack *sqs){
    sqs->top = -1;
}

int StackEmpty(SqStack *sqs){
    SqStack sq = *sqs;
    if (sq.top == -1) {
        return 1;
    }else{
        return 0;
    }
}
int Push(SqStack *sqs, char x){
//    不能用这个，这个类似浅拷贝，只会在本函数作用域内修改
//    SqStack sq = *sqs;
    if (sqs->top == kMaxStackLen-1) {
        return  0;
    }
    sqs->data[++sqs->top] = x;
    return  1;
}
int Pop(SqStack *sqs, char *x){
//    SqStack sq = *sqs;
    if (sqs->top == -1) {
        return  0;
    }
    *x = sqs->data[sqs->top--];
    return 1;
}
int GetTop(SqStack *sqs, char *x){
    SqStack sq = *sqs;
    if (sq.top == -1) {
        return  0;
    }
    *x = sq.data[sq.top];
    return 1;
}
int pushStk(stkopt opt){
    int i = opt.i;
    stk *s = opt.s;
    int x = opt.x;
    if (i<0 || i>1) {
// 栈号不正确
        return  1;
    }
    if (s->top[1]-s->top[0]==1) {
//        栈满
        return  2;
    }
    switch (i) {
        case 0:{
            s->stack[++s->top[0]]=x;
            return 0;
        }break;
        case 1:{s->stack[--s->top[1]]=x;
            return 0;
        }break;
    }
    return 0;
}
void initStk(stk *s){
//    stk ss = *s; 是对stk的浅拷贝，并不会修改s里的内容
//    ss.top[0] = -1;    ss.top[1] = kMaxStackLen;
    s->top[0] = -1;
    s->top[1] = kMaxStackLen;
}
int popStk(stkopt *opt){
    stk *s  = opt->s;
    int i = opt->i;
    int *x = &opt->x;
    if (i<0 || i>1) {
        // 栈号不正确
        return  1;
    }
    switch (i) {
        case 0:{
            if(s->top[0]==-1){
                // 栈空
                return 2;
            }else{
               *x = s->stack[s->top[0]--];
                return 0;
            }
        }break;
        case 1:{
            if (s->top[1]==kMaxStackLen-1) {
                return 2;
            }else{
                *x = s->stack[s->top[1]++];
                return  0;
            }
        }break;
    }
    return  0;
}
// 指针栈，存放通用类型
SPStack initSPStack(void){
//    BiNodeP *data = malloc(kMaxStackLen *sizeof(BiNodeP));
    SPStack S = malloc(sizeof(SPStack));
    S->top = -1;
    return  S;
}
int PushP(SPStack sqs, BiTree x){
    if (sqs->top == kMaxStackLen-1) {
        return  0;
    }
    sqs->data[++sqs->top] = x;
    return  1;
}
int PopP(SPStack sqs, BiTree *x){
    if (sqs->top == -1) {
        return  0;
    }
    *x = sqs->data[sqs->top--];
    return 1;
}
int GetPTop(SPStack sqs, BiTree *x){
    if (sqs->top == -1) {
        return  0;
    }
    *x = sqs->data[sqs->top];
    return 1;
}
int StackPEmpty(SPStack sqs){
    if (sqs->top == -1) {
        return 1;
    }else{
        return 0;
    }
}
